######################################################################
# Time-stamp: <03/10/26 18:53:10 ostolop>
#
# Routines to log things.
######################################################################
package EP::Session::Log;
use strict;

use CGI;
use XML::LibXML;

use EP::Config;

=head1 NAME

EP_UI_XML::SessionLog - Write various output to the session log file.

=head1 SYNOPSIS

C<my $slog = EP_UI_XML::SessionLog->new ( "log.xml" );>
C<$slog->write_log ( "message", "error" );>

=head1 DESCRIPTION

=head1 METHODS

=over

=item

=back

=cut

my $ep_log_XML = <<__EPLOGXML__;
<?xml version="1.0"?>
<ep_log/>
__EPLOGXML__

sub new {
  my $proto = shift;
  my $class = ref($proto) || $proto;
  my $self  = {};
  bless $self, $class;

  $self->initialize ();
  return $self;
}

sub initialize {
  my $self = shift;

  $self->{xml_parser} = XML::LibXML->new();
  $self->{log_doc} = $self->{xml_parser}->parse_string ( $ep_log_XML );
}

sub write_log {
  my $self     = shift;
  my ($message, $severity) = @_;

  my $log_doc = $self->{log_doc};

  my $root = $log_doc->getDocumentElement();
  $root->appendChild ( $self->create_entry ( $log_doc, $message, $severity ) );
}

sub dump_log {
  my $self = shift;
  my $log_file = shift;

  $self->{log_doc}->toFile ( $log_file, 2 );
}

=item create_entry

Creates a log entry with a severity of C<$severity> and the content
C<$message>, which can be a piece of text, or some form of an
C<XML::LibXML:Document>, or any object possessing the
C<getDocumentElement()> call, returning an C<XML::LibXML::Document>

=cut

######################################################################
sub create_entry {
  my $self = shift;
  my ( $doc, $message, $severity ) = @_;
  chomp (my $date =  `date +"%D %H:%M:%S"`);

  my $log_entry = $doc->createElement( "entry" );
  $log_entry->setAttribute ( "date", $date );
  $log_entry->setAttribute ( "severity", $severity );

  if ( not ref($message) ) {
    $log_entry->appendChild ( $doc->createTextNode ( $message ) );
  } elsif ( defined ($message->getDocumentElement) ) {
    $log_entry->appendChild ( $message->getDocumentElement() );
  } else {
    die "Don't know what to do with $message!\n";
  }

  return $log_entry;
}

1;
